#include "StdAfx.h"
#include "Polygon.h"


using namespace System;
using namespace System::Collections;


Polygon::Polygon() {
	points = gcnew ArrayList();
	sides = gcnew ArrayList();
	isFinal = false;
}

void Polygon::addPoint(int x, int y) {
	array<int>^ p = gcnew array<int>(2);
	p[0] = x;
	p[1] = y;
	points->Add(p);
}

bool Polygon::setFinal() {

	int pointCount = getPointCount();

	if (!isFinal && (pointCount > 2)) {
		isFinal = true;

		// Seiten + Bounding-Box berechnen

		int iterator = 0;
		array<int>^ firstPoint;
		array<int>^ lastPoint;
		array<int>^ beforePoint;

		int tempMinX = Int32::MaxValue;
		int tempMaxX = Int32::MinValue;
		int tempMinY = Int32::MaxValue;
		int tempMaxY = Int32::MinValue;

		IEnumerator^ myEnum = points->GetEnumerator();
		while (myEnum->MoveNext()) {
			array<int>^ point = safe_cast<array<int>^>(myEnum->Current);
			if (iterator == 0) {
				firstPoint = point;	
			} else {
				array<int,2>^ side = gcnew array<int,2>(2,2);
				side[0,0] = beforePoint[0];		// Punkt1 X
				side[0,1] = beforePoint[1];		// Punkt1 Y
				side[1,0] = point[0];			// Punkt2 X
				side[1,1] = point[1];			// Punkt2 Y
				sides->Add(side);
				if (iterator == pointCount-1) {
					lastPoint = point;
				}
			}
			beforePoint = point;
			iterator++;

			if (point[0] < tempMinX) tempMinX = point[0];
			if (point[0] > tempMaxX) tempMaxX = point[0];
			if (point[1] < tempMinY) tempMinY = point[1];
			if (point[1] > tempMaxY) tempMaxY = point[1];
		}

		array<int,2>^ side = gcnew array<int,2>(2,2);
		side[0,0] = lastPoint[0];
		side[0,1] = lastPoint[1];
		side[1,0] = firstPoint[0];
		side[1,1] = firstPoint[1];
		sides->Add(side);

		minX = tempMinX;
		maxX = tempMaxX;
		minY = tempMinY;
		maxY = tempMaxY;


		return true;

	} else {
		return false;
	}
	
}

void Polygon::clear() {
	isFinal = false;
	points->Clear();
	sides->Clear();
	minX = maxX = minY = maxY = 0;
}

int Polygon::getPointCount() {
	return points->Count;
}

int Polygon::getSideCount() {
	return sides->Count;
}

int Polygon::getMinX() {
	return minX;
}

int Polygon::getMaxX() {
	return maxX;
}

int Polygon::getMinY() {
	return minY;
}

int Polygon::getMaxY() {
	return maxY;
}
